class EventBus {
  constructor() {
    this.events = {};  // 存储事件及其订阅者
    this.cache = {};   // 缓存未处理的事件
  }

  // 订阅事件
  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(listener);

    // 处理缓存中的事件
    if (this.cache[event]) {
      listener(this.cache[event]);
      delete this.cache[event];
    }
  }

  // 取消订阅事件
  off(event, listener) {
    if (!this.events[event]) return;

    this.events[event] = this.events[event].filter(l => l !== listener);
    if (this.events[event].length === 0) {
      delete this.events[event];  // 删除空的事件数组
    }
  }

  // 触发事件
  emit(event, data) {
    const listeners = this.events[event];

    if (!listeners || listeners.length === 0) {
      // 缓存未处理的事件
      this.cache[event] = data;
    } else {
      listeners.forEach(listener => listener(data));
    }
  }
}

module.exports = new EventBus();